package com.yijiaw.service;

import com.yijiaw.dao.MessageDAO;

import com.yijiaw.domain.Message;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

/**
 * Spring service that handles CRUD requests for Message entities
 * 
 */

@Service("MessageService")
@Transactional
public class MessageServiceImpl implements MessageService {

	/**
	 * DAO injected by Spring that manages Message entities
	 * 
	 */
	@Autowired
	private MessageDAO messageDAO;

	/**
	 * Instantiates a new MessageServiceImpl.
	 *
	 */
	public MessageServiceImpl() {
	}

	/**
	 * Load an existing Message entity
	 * 
	 */
	@Transactional
	public Set<Message> loadMessages() {
		return messageDAO.findAllMessages();
	}

	/**
	 * Return a count of all Message entity
	 * 
	 */
	@Transactional
	public Integer countMessages() {
		return ((Long) messageDAO.createQuerySingleResult("select count(o) from Message o").getSingleResult()).intValue();
	}

	/**
	 * Return all Message entity
	 * 
	 */
	@Transactional
	public List<Message> findAllMessages(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Message>(messageDAO.findAllMessages(startResult, maxRows));
	}

	/**
	 */
	@Transactional
	public Message findMessageByPrimaryKey(Integer id) {
		return messageDAO.findMessageByPrimaryKey(id);
	}

	/**
	 * Delete an existing Message entity
	 * 
	 */
	@Transactional
	public void deleteMessage(Message message) {
		messageDAO.remove(message);
		messageDAO.flush();
	}

	/**
	 * Save an existing Message entity
	 * 
	 */
	@Transactional
	public void saveMessage(Message message) {
		Message existingMessage = messageDAO.findMessageByPrimaryKey(message.getId());

		if (existingMessage != null) {
			if (existingMessage != message) {
				existingMessage.setId(message.getId());
				existingMessage.setName(message.getName());
				existingMessage.setCompany(message.getCompany());
				existingMessage.setPhone(message.getPhone());
				existingMessage.setContent(message.getContent());
				existingMessage.setDate(message.getDate());
			}
			message = messageDAO.store(existingMessage);
		} else {
			message = messageDAO.store(message);
		}
		messageDAO.flush();
	}
}
